package itsm.isperp.module.controller.db;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.domain.CountQuery;
import itsm.isperp.framework.web.request.DefaultCountQuery;
import itsm.isperp.framework.web.request.JqGridFilterRule;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.db.DbEntity;
import itsm.isperp.module.entity.db.DbEntityDatalog;
import itsm.isperp.module.entity.db.DbEntityField;
import itsm.isperp.module.entity.db.DbEntitySlmMonitorMap;
import itsm.isperp.module.service.configuration.ConfCiPropertyDatalogService;
import itsm.isperp.module.service.db.DbEntityDatalogService;
import itsm.isperp.module.service.db.DbEntityFieldService;
import itsm.isperp.module.service.db.DbEntityService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 实体模型控制器
 * 
 * @author lizx
 * @date 2013-5-5
 */
@Controller
@RequestMapping("db/entity")
public class DbEntityController extends BaseController<DbEntity> {

	@Autowired
	DbEntityService dbEntityService;

	@Autowired
	DbEntityFieldService dbEntityFieldService;

	@Autowired
	DbEntityDatalogService dbEntityDatalogService;

	@Override
	public DbEntityService getService() {
		return dbEntityService;
	}

	@Override
	public String getPageTitle() {
		return "实体模型管理";
	}

	@ResponseBody
	@RequestMapping("listEntityField")
	public List<DbEntityField> listEntityField(String name) {
		return this.dbEntityFieldService.findAllByEntityName(name);
	}

	/**
	 * 用于下拉选择试题字段
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping("selectEntityFieldById")
	public List<DbEntityField> selectEntityFieldById(String id) {
		return this.dbEntityFieldService.findAllByEntityId(id, new String[] {
				"name", "columnName" }, new JqGridFilterRule(
				"slm_calculate_field", JqGridFilterRuleOp.eq, "1"));
	}

	@ResponseBody
	@RequestMapping("generateDbEntityField")
	public ResultMessage generateDbEntityField(String id) {
		return this.dbEntityService.generateDbEntityField(id);
	}

	@ResponseBody
	@RequestMapping("showTables")
	public List<Map<String, Object>> showTables(JqGridRequest request) {
		return this.dbEntityService.showTables(request);
	}

	@ResponseBody
	@RequestMapping("showColumns")
	public List<Map<String, Object>> showColumns(String id,
			JqGridRequest request) {
		return this.dbEntityService.showColumns(id, request);
	}

	@RequestMapping("typeMenu")
	@ResponseBody
	public ITreeNode[] typeMenu() {
		return this.getTypeCountQuery().getTreeNodes("按实体分类");
	}

	protected CountQuery getTypeCountQuery() {

		CountQuery cq = new DefaultCountQuery("db_entity");

		List<Object> types = this.getService().findAllType();

		for (Object obj : types) {
			cq.addCountFilter(obj.toString(),
					" entity_category='" + obj.toString() + "' ");
		}
		return cq;

	}

	@RequestMapping("list")
	@ResponseBody
	@Override
	public PageResponse<DbEntity> list(JqGridRequest request,
			HttpServletRequest req) {
		return super.list(request, req);
	}

	@RequestMapping("edit")
	@Override
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = this.getModelAndView();

		DbEntity model = null;
		String slmDesc = "未设定";
		if (StringUtils.isEmpty(id)) {
			model = new DbEntity();
			model.setId(HibernateUUIDGenerator.generate());

		} else {

			model = this.getService().findOne(id);
			if (model.getUseForSlm()) {

				// 取得关联的数据映射关系
				List<Map<String, Object>> maps = this.getService()
						.getSlmMonitorMapList(model.getTableName(),
								model.getSlmMonitorColumn());
				if (CollectionUtils.isNotEmpty(maps)) {
					slmDesc = "【监控字段：" + model.getSlmMonitorColumn()
							+ "；     状态映射关系：";
					for (Map<String, Object> obj : maps) {
						Object columnNameObj = obj.get("column_name");
						if (columnNameObj != null)
							slmDesc += obj.get("status") + "(" + columnNameObj
									+ "),";
					}
					slmDesc += "】";
				}

			}

		}
		mv.addObject("slmDesc", slmDesc);
		mv.addObject("model", model);
		return mv;
	}

	@RequestMapping("monitorMapList")
	@ResponseBody
	public List<Map<String, Object>> monitorMapList(String tableName,
			String columnName) {

		// 取得关联的数据映射关系
		List<Map<String, Object>> maps = this.getService()
				.getSlmMonitorMapList(tableName, columnName);

		return maps;
	}

	@RequestMapping("monitorMapEdit")
	public ModelAndView monitorMapEdit(String tableName, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = this.getModelAndView();
		JqGridRequest request = new JqGridRequest();
		request.isQueryOne(true);
		request.addFilterRule("table_name", JqGridFilterRuleOp.eq, tableName);

		request.setSelectColumns("id", "table_name", "slm_monitor_column",
				"slm_rely_table_name");

		DbEntity model = this.getService().findAll(request).get(0);

		List<Map<String, Object>> maps = this.getService()
				.getSlmMonitorMapList(tableName, model.getSlmMonitorColumn());
		mv.addObject("maps", maps);
		mv.addObject("mapsSize", maps == null ? 0 : maps.size());
		mv.addObject("model", model);
		mv.addObject("tableName", tableName);
		return mv;
	}

	@RequestMapping("saveMonitorMap")
	@ResponseBody
	public ResultMessage saveMonitorMap(String tableName,
			String slmMonitorColumn, String slmRelyTableName,
			HttpServletRequest req) {

		String mapsSizeStr = req.getParameter("mapsSize");
		if (StringUtils.isEmpty(mapsSizeStr)) {
			return ResultMessage.failure();
		}
		int mapsSize = Integer.parseInt(mapsSizeStr);
		// 组装列表
		List<DbEntitySlmMonitorMap> list = new ArrayList<>();
		for (int i = 0; i < mapsSize; i++) {
			String status = req.getParameter("status" + i);
			String columnName = req.getParameter("columnName" + i);
			DbEntitySlmMonitorMap map = new DbEntitySlmMonitorMap();
			map.setColumnName(columnName);
			map.setStatus(status);
			list.add(map);
		}

		this.getService().saveMonitorMap(tableName, slmMonitorColumn,
				slmRelyTableName, list);

		return ResultMessage.success();
	}

	@RequestMapping("save")
	@ResponseBody
	@Override
	public ResultMessage save(DbEntity model, HttpServletRequest req) {

		return super.save(model, req);
	}

	@RequestMapping("getDatalogByBusinessId/{businessId}")
	@ResponseBody
	public List<DbEntityDatalog> getDatalogByBusinessId(
			@PathVariable("businessId") String businessId) {
		return dbEntityDatalogService.findByBusinessId(businessId);
	}

	@RequestMapping("getCiDatalogByBusinessId/{businessId}")
	@ResponseBody
	public List<Map<String, Object>> getCiDatalogByBusinessId(
			@PathVariable("businessId") String businessId) {
		ConfCiPropertyDatalogService confCiPropertyDatalogService = ContextHolder
				.getSpringBean("confCiPropertyDatalogService");

		return confCiPropertyDatalogService.findByBusinessId(businessId);
	}

}
